// Copyright (c) 2024-present AI-Labs

import { EditorEvents } from "@tiptap/core";

import { t } from "i18next";
import mammoth from "mammoth/mammoth.browser";

import { UAIEditorEventListener, UAIEditorOptions } from "@uai-team/uai-editor-common";
import { MenuButton, MenuButtonOptions } from "@uai-team/uai-editor-common";

import { WordIcon } from "@uai-team/uai-editor-common";

/**
 * 基础菜单：导入Word
 */
export class ImportWord extends HTMLElement implements UAIEditorEventListener {
    // 按钮选项
    menuButtonOptions: MenuButtonOptions = {
        menuType: "button",
        enable: true,
        icon: WordIcon,
        hideText: true,
        text: t('base.importWord.text'),
        tooltip: t('base.importWord.text'),
    }

    // 功能按钮
    menuButton: MenuButton;

    constructor(options: MenuButtonOptions) {
        super();

        // 初始化功能按钮选项
        this.menuButtonOptions = { ...this.menuButtonOptions, ...options };

        // 创建功能按钮
        this.menuButton = new MenuButton(this.menuButtonOptions);
    }

    /**
     * 定义创建方法
     * @param event 
     * @param options 
     */
    onCreate(event: EditorEvents["create"], options: UAIEditorOptions) {
        this.menuButton.onCreate(event, options);
        this.appendChild(this.menuButton);

        // 定义按钮点击事件，打印内容
        this.addEventListener("click", () => {
            if (this.menuButtonOptions.enable) {
                event.editor.commands.blur();
                // 初始化文件选择
                const fileInput = document.createElement("input");
                fileInput.type = "file";
                fileInput.multiple = false;
                // 修改文件选择器的 accept 属性，只允许选择 Word 文件
                fileInput.accept = ".doc,.docx";

                fileInput.addEventListener("change", async () => {
                    for (const file of fileInput.files ?? []) {
                        const { value } = await mammoth.convertToHtml({ arrayBuffer: file.arrayBuffer() });

                        try {
                            // 解析和加工 Mammoth 返回的 HTML 内容
                            const domparser = new DOMParser();
                            const doc = domparser.parseFromString(value, 'text/html');
                            for (const img of doc.querySelectorAll('img')) {
                                const parent = img.parentElement
                                if (parent?.tagName === 'P') {
                                    parent.insertAdjacentElement('beforebegin', img);
                                    if (!parent.hasChildNodes() && parent.textContent === '') {
                                        parent.remove();
                                    }
                                }
                            }
                            const content = doc.body.innerHTML.toString();
                            event.editor.commands.setContent(content);
                        } catch {
                        }
                    }
                });

                fileInput.click();
            }
        })
    }

    /**
     * 定义Transaction监听方法
     * @param event 
     * @param options 
     */
    onTransaction(event: EditorEvents["transaction"], options: UAIEditorOptions) {
        this.menuButton.onTransaction(event, options);
    }

    onEditableChange(editable: boolean) {
        this.menuButtonOptions.enable = editable;
        this.menuButton.onEditableChange(editable);
    }
}
